package home.game.client.display.panels;

import home.game.client.controllers.Application;
import home.game.entity.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;

/**
 */
public class UserPanel extends Observable {
    private JDialog dialog;
    private User user;
    private JTextField nameField;

    public void showLogin() {
        dialog = new JDialog();
        dialog.setLayout(new GridLayout(2, 2));
        nameField = new JTextField();
        dialog.add(nameField);
        final JButton create = new JButton("Login");
        create.addActionListener(new EnterUser());
        create.setEnabled(false);
        nameField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (nameField.getText() == null || (nameField.getText().length() < 1 && e.getKeyCode() != KeyEvent.VK_BACK_SPACE)) {
                    create.setEnabled(false);
                } else {
                    create.setEnabled(true);
                }
            }
        });
        dialog.setLocation((int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2), (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2));
        dialog.add(create);
        dialog.setSize(100, 100);
        dialog.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        dialog.setVisible(true);
    }

    private class EnterUser extends AbstractAction {

        public EnterUser() {

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            User existing = Application.getInstance().getUserManager().findUser(nameField.getText());
            if (existing.getId() != 0) {
                user = existing;
            } else {
                user = new User();
                user.setPlayerName(nameField.getText());
            }
            setChanged();
            notifyObservers(user);
            dialog.dispose();
        }
    }
}
